import 'package:flutter/material.dart';
import 'package:xindong/utils/xindong_image_util.dart';
import 'package:xindong/widgets/image/browser/xindong_images_browser.dart';

// 图片浏览
class XinDongDongTaiImageView extends StatelessWidget {
  final List dataList; // 数据源
  final double viewWidth; // 宽度
  final double radius = 5.0; // 圆角
  final double spacing = 5.0; // 视图间隙
  final int maxColumns = 3; // 视图宽度
  final double itemRatio = 114 / 142;

  const XinDongDongTaiImageView({Key? key, required this.dataList, required this.viewWidth}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (dataList.isEmpty) {
      return const SizedBox();
    }
    return Wrap(
      spacing: spacing,
      runSpacing: spacing,
      alignment: WrapAlignment.start,
      crossAxisAlignment: WrapCrossAlignment.start,
      children: buildWidgetList(),
    );
  }

  List<Widget> buildWidgetList() {
    final double itemWidth = (viewWidth - spacing * (maxColumns - 1)) / maxColumns;
    List<Widget> list = [];
    List sizeList = generateSizeList(itemWidth);
    for (int i = 0; i < dataList.length; i++) {
      var object = dataList[i];
      Size size = sizeList[i];
      list.add(buildItemWidget(object, size, i));
    }
    return list;
  }

  List<Size> generateSizeList(double itemWidth) {
    switch (dataList.length) {
      case 1:
        {
          double width = itemWidth * 1.5;
          double height = width / itemRatio;
          return [Size(width, height)];
        }
      case 2:
        {
          double width = itemWidth * 1.35;
          double height = width / itemRatio;
          return [
            Size(width, height),
            Size(width, height),
          ];
        }
      case 4:
        {
          double width = itemWidth * 1.25;
          double height = width / itemRatio;
          return [
            Size(width, height),
            Size(width, height),
            Size(width, height),
            Size(width, height),
          ];
        }
      default:
        double width = itemWidth;
        double height = width / itemRatio;
        return dataList.map((e) => Size(width, height)).toList();
    }
  }

  // item
  Widget buildItemWidget(var object, Size size, int index) {
    String urlString;
    if (object is String) {
      urlString = object;
    } else {
      return const Text('Un support');
    }
    return Container(
      width: size.width,
      height: size.height,
      clipBehavior: Clip.antiAlias,
      decoration: BoxDecoration(color: Colors.transparent, borderRadius: BorderRadius.circular(radius)),
      child: GestureDetector(
        onTap: object is String ? () => XinDongImagesBrowser.show(list: dataList, currentIndex: index) : null,
        child: ImageUtil.networkImageUrl(urlString, fit: BoxFit.cover),
      ),
    );
  }
}
